
#include <mntent.h>
#include <sys/vfs.h>
#include "appinc.h"



int libfd_set_nonblock(int fd, bool nonblock)
{
	int ret, fl, fln;

	fl = fcntl(fd, F_GETFL, 0);
	if (fl < 0)
		return fl;
	
	if (nonblock)
		fln = fl | O_NONBLOCK;
	else
		fln = fl & ~O_NONBLOCK;
	if (fl == fln)
		return 0;
	
	ret = fcntl(fd, F_SETFL, fln);
	if (ret < 0)
		return ret;

	return 0;
}
/* 获取文件的大小 */
long libfile_get_size(const char *name)
{
	FILE *fp;
	
	if (name == NULL)
		return -1;
	
	fp = fopen(name, "rb");
	if (fp == NULL)
		return -1;
	fseek(fp, 0, SEEK_END);
	long size =  ftell(fp);
	fclose(fp);

	return size;
}

/* 从文件中读取数据 */
int libfile_read_data(const char *file, void *data, int size)
{
	int fd, len;

	fd = open(file, O_RDONLY);
	if (fd < 0)
		return fd;
	len = read(fd, data, size);
	close(fd);

	return len;
}

/* 将数据写入文件 */
int libfile_write_data(const char *file, void *data, int size)
{
	int fd, len;

	fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if (fd < 0)
		return fd;
	flock(fd, LOCK_EX);
	len = write(fd, data, size);
	flock(fd, LOCK_UN);
	
	close(fd);

	return len;
}

